package com.tms.app.tms.ui;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.sdk.android.ams.common.util.StringUtil;
import com.bigkoo.pickerview.TimePickerView;
import com.tms.app.tms.R;
import com.tms.app.tms.bean.UserInfo;
import com.tms.app.tms.bean.response.BaseResponse;
import com.tms.app.tms.bean.response.UserInfoRes;
import com.tms.app.tms.ui.base.ui.AbsPhotoPickWithPs;
import com.tms.app.tms.ui.home.me.UserInfoPresenter;
import com.tms.app.tms.utils.SharePreferenceUtil;
import com.tms.app.tms.utils.TimeUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.edu.zafu.camera.activity.CameraIdCradActivity;

import static com.tms.app.tms.utils.TimeUtil.getTimeYMD;

/**
 * Created by Administrator on 2017/10/27 0027.
 */

public class InfoCarActivity extends AbsPhotoPickWithPs {


    @BindView(R.id.text_car_number)
    EditText textCarNumber;
    @BindView(R.id.text_car_name)
    EditText textCarName;
    @BindView(R.id.text_buy_car_time)
    TextView textBuyCarTime;
    @BindView(R.id.text_car_sever)
    EditText textCarSever;
    @BindView(R.id.button_send)
    Button buttonSend;
    private int requestType;
    private boolean isFrist = true;
    private int CAR_RESULT_OK=0x323;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);

        presenter = new UserInfoPresenter();
        requestType = getIntent().getIntExtra("requestType", 0);
        if (requestType == 0)
            setToolBarTitle("主车资料", -1, 0);
        else
            setToolBarTitle("挂车资料", -1, 0);
        userInfo = SharePreferenceUtil.getObject(this, UserInfo.class);
        if (userInfo == null)
            userInfo = new UserInfo();
        bindDataToView(userInfo);
    }

    @Override
    public void initLayout() {
        setContentView(R.layout.activity_info_car);
    }

    @Override
    public List<Integer> intitImgBg() {
        List<Integer> imgResList = getImgResList();
        imgResList.clear();
        imgResList.add(R.mipmap.idcard_font);
        imgResList.add(R.mipmap.move_card_res);
        return imgResList;
    }


    @OnClick({R.id.text_buy_car_time, R.id.button_send,R.id.img_res_1,R.id.img_res_3})
    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.text_scan:
                Intent intent = new Intent(this, CameraIdCradActivity.class);
                startActivity(intent);
                break;
            case R.id.img_idcard_1:
            case R.id.img_idcard_2:
            case R.id.img_driver:

                break;
            case R.id.toolbar_left:
                finish();
                break;
            case R.id.text_buy_car_time:
                pickTime();
                break;
            case R.id.button_send:
                saveCar();
                break;
            case R.id.img_res_1:
                break;
            case R.id.img_res_3:
                intent=new Intent(this,ShowPhotoActivity.class);
                intent.putExtra("imgPath" , R.mipmap.move_card);
                intent.putExtra("imgType",1);
                startActivity(intent);
        }
    }

    private void saveCar() {
        String number = textCarNumber.getText().toString();
        String brand = textCarName.getText().toString();
        String buyTime = textBuyCarTime.getText().toString().replace("-", "");
        String serverLift = textCarSever.getText().toString();
        String img;
        if (requestType == 0) {
            userInfo.setCarLicense(textCarNumber.getText().toString());
            userInfo.setHead_brand(textCarName.getText().toString());
            try {
                userInfo.setHead_buy_time(Long.parseLong(buyTime));
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            userInfo.setHead_service_life(textCarSever.getText().toString());
            img = userInfo.getHead_license_img();
        } else {
            userInfo.setTrailerNumber(textCarNumber.getText().toString());
            userInfo.setTrailer_brand(textCarName.getText().toString());
            try {
                userInfo.setTrailer_buy_time(Long.parseLong(buyTime));
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            userInfo.setTrailer_service_life(textCarSever.getText().toString());
            img = userInfo.getTrailer_license_img();
        }
        userInfo.moveCardA = selectImgList.get(imgViewList2.get(1));

        if (number == null || number.length() < 1) {
            showMsg("请输入车牌号");
            return;
        }
        if (brand == null || brand.length() < 1) {
            showMsg("请输入车辆品牌");
            return;
        }
        if (buyTime.length() < 2) {
            showMsg("请输入购车年限");
            return;
        }
        if (serverLift.length() < 1) {
            showMsg("请输入服务年限");
            return;
        }


        if (!StringUtil.isEmpty(img) || selectImgList.size() > 0) {

        } else {
            showMsg("请上传证件");
            return;
        }
        presenter.updateCar(userInfo, requestType);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void subscribe(UserInfoRes userInfoRes) {
        if (userInfoRes.getCode()==200){
            if (userInfoRes.getRequestType() == 3 || userInfoRes.getRequestType() == 4){
                setResult(CAR_RESULT_OK);
                showMsg("保存成功");
                SharePreferenceUtil.saveObject(this,userInfo);
                finish();
            }else {
                bindDataToView(userInfoRes.getData());
            }
        }else {
            showMsg(userInfoRes.getError());
        }
    }

    private void bindDataToView(UserInfo userInfo) {
        if (requestType == 0) {
            textCarNumber.setText(userInfo.getCarLicense());
            textCarName.setText(userInfo.getHead_brand());
            textBuyCarTime.setText(TimeUtil.getTimeFormat(userInfo.getHead_buy_time()));
            textCarSever.setText(userInfo.getHead_service_life());
            showServerImg(userInfo.getHead_license_img(),userInfo.getHead_license_img());
            if (userInfo.getHead_auth_status() == 1) {
                buttonSend.setVisibility(View.GONE);
                textCarNumber.setEnabled(false);
                textCarName.setEnabled(false);
                textBuyCarTime.setEnabled(false);
                textCarSever.setEnabled(false);
            } else {
                buttonSend.setVisibility(View.VISIBLE);
                textCarNumber.setEnabled(true);
                textCarName.setEnabled(true);
                textBuyCarTime.setEnabled(true);
                textCarSever.setEnabled(true);
            }
        } else {
            textCarNumber.setText(userInfo.getTrailerNumber());
            textCarName.setText(userInfo.getTrailer_brand());
            textBuyCarTime.setText(TimeUtil.getTimeFormat(userInfo.getTrailer_buy_time()));
            textCarSever.setText(userInfo.getTrailer_service_life());
            showServerImg(userInfo.getTrailer_license_img(),userInfo.getTrailer_license_img());
            if (userInfo.getTrailer_auth_status() == 1) {
                buttonSend.setVisibility(View.GONE);
                textCarNumber.setEnabled(false);
                textCarName.setEnabled(false);
                textBuyCarTime.setEnabled(false);
                textCarSever.setEnabled(false);
            } else {
                buttonSend.setVisibility(View.VISIBLE);
                textCarNumber.setEnabled(true);
                textCarName.setEnabled(true);
                textBuyCarTime.setEnabled(true);
                textCarSever.setEnabled(true);
            }
        }

    }


    public void pickTime() {
        //时间选择器
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        //startDate.set(2013,1,1);
        Calendar endDate = Calendar.getInstance();
        //endDate.set(2020,1,1);

        //正确设置方式 原因：注意事项有说明
        startDate.set(1990, 0, 1);
        // endDate.set(2020,11,31);

        TimePickerView pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                textBuyCarTime.setText(getTimeYMD(date));
            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确认")//确认按钮文字
                .setContentSize(18)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                // .setTitleText("Title")//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(Color.BLUE)//确定按钮文字颜色
                .setCancelColor(Color.BLUE)//取消按钮文字颜色
                .setTitleBgColor(0xFF0081C2)//标题背景颜色 Night mode
                .setBgColor(0xFF0081C2)//滚轮背景颜色 Night mode
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                // .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .setLabel("年", "月", "日", "", "", "")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(true)//是否显示为对话框样式
                .build();
        pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
        pvTime.show();
    }


}
